import { uploadUtil } from './../util/upload.util';
import { Injectable, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Cron, CronExpression } from '@nestjs/schedule';
import { HealthCheckService } from '@nestjs/terminus';
import path from 'path';
import ioRedis from 'ioredis';
import Piscina from 'piscina';
import config from 'src/config/config';

@Injectable()
export class CommonService {
  public UserTokenClient: ioRedis;
  public PaymentClient: ioRedis;
  public CacheClient: ioRedis;
  private piscina: Piscina;

  constructor(private jwtService: JwtService, private health: HealthCheckService, private uploadService: uploadUtil) {
    this.piscina = new Piscina({
      filename: path.resolve(__dirname, 'HighCpuMission.js'),
      maxThreads: 50,
    });
    this.redisConnect();
  }

  /**
   * @author nie
   * @description 开启线程，一般用于处理cpu密集任务
   * @email a896211755@gmail.com
   */
  async runTask(data: { name: string; params: any }): Promise<any> {
    return await this.piscina.run(data);
  }

  /**
   * @author nie
   * @description 获取登录token
   * @param user_id 用户id
   * @email a896211755@gmail.com
   */
  async loginSign(user_id: any): Promise<string> {
    let payload = {
      id: user_id,
    };
    // let val =  await this.cacheManager.get(String(2))
    let token: string = this.jwtService.sign(payload);
    console.log(token, 'token');
    await this.UserTokenClient.set(String(user_id), token, 'EX', 60 * 60 * 10);
    return token;
  }

  /**
   * @author nie
   * @description 解析token
   * @email a896211755@gmail.com
   */
  checkToken(token: string) {
    return this.jwtService.verify(token);
  }

  /**
   * @author nie
   * @description 定时任务
   * @email a896211755@gmail.com
   */
  @Cron(CronExpression.EVERY_SECOND)
  handleCron() {}

  async redisConnect() {
    let logger = new Logger();
    let redis = new ioRedis(config.REDIS_URL);
    this.UserTokenClient = new ioRedis({
      host: config.REDIS_HOST,
      username: config.REDIS_USER,
      password: config.REDIS_PASSWORD,
      db: 1,
    });
    this.UserTokenClient.on('connect', (val) => {
      logger.log('userRedisToken', 'RedisLoader');
    });
    this.UserTokenClient.on('error', (err) => {
      logger.error(err, 'RedisLoader');
    });
    this.PaymentClient = new ioRedis({
      host: config.REDIS_HOST,
      username: config.REDIS_USER,
      password: config.REDIS_PASSWORD,
      db: 2,
    });
    //  this.PaymentClient.addListener('')
    this.PaymentClient.on('error', (err) => {
      logger.error(err, 'PaymentLoader');
    });

    this.CacheClient = new ioRedis({
      host: config.REDIS_HOST,
      username: config.REDIS_USER,
      password: config.REDIS_PASSWORD,
      db: 3,
    });

    this.CacheClient.on('error', (err) => {
      logger.error(err, 'CaCheLoader');
    });
    this.CacheClient.on('connect', (val) => {
      logger.log('CacheClient', 'CaCheLoader');
    });
  }

  async uploadFile(file: Express.Multer.File) {
    return await this.uploadService.upload(file.buffer, file.originalname);
  }
}
